<template>
  <div class="header">
    <el-header class="container">
      <el-menu
        :default-active="1"
        class="el-menu-demo"
        mode="horizontal"
        background-color="#0d1e67"
        text-color="#fff"
        active-text-color="#ffd04b"
        style="text-align: right"
        @select="handleSelect"
      >
        <el-menu-item index="0" @click="$router.push({ path: '/index' })"
          ><img class="img-fluid" :src="$imgURL + 'loginLogo.png'" alt="img"
        /></el-menu-item>
        <el-menu-item index="1" @click="$router.push({ path: '/index' })">
          首页
        </el-menu-item>
        <el-menu-item
          index="2"
          @click="$router.push({ path: '/userCenter?activeName=first' })"
        >
          个人中心
        </el-menu-item>
        <el-menu-item
          index="3"
          @click="$router.push({ path: '/link-release?activeName=first' })"
        >
          链上市场
        </el-menu-item>
        <el-menu-item index="4" @click="$router.push({ path: '/honor' })">
          荣誉榜
        </el-menu-item>
        <!-- <el-menu-item index="5" @click="$router.push({ path: '/help' })">
          微网系统
        </el-menu-item>
        <el-menu-item index="6" @click="$router.push({ path: '/contact' })">
          联系我们
        </el-menu-item> -->
        <el-submenu index="7">
          <template slot="title">其他平台</template>
          <el-menu-item index="7-1" @click="toPath1"> 碳迹追踪 </el-menu-item>
          <el-menu-item index="7-2" @click="toPath2"> 拓扑平台 </el-menu-item>
        </el-submenu>

        <div v-if="!isLogin" class="headerbtnbox" style="display: flex">
          <el-button class="login-btn" @click="loginVisible = true"
            >登 录</el-button
          >
          <el-button type="primary" @click="regVisible = true">注 册</el-button>
        </div>

        <div v-else class="headerbtnbox">
          <img :src="$imgURL + 'user.png'" class="userImg" alt="头像" />
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              {{ userDate.name }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">
                <router-link :to="'/userCenter?activeName=first'"
                  >个人中心</router-link
                >
              </el-dropdown-item>
              <el-dropdown-item command="2">退出系统</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-menu>
    </el-header>

    <el-dialog title="登 录" :visible.sync="loginVisible" width="800px">
      <el-form ref="loginDto" :model="loginDto" label-width="80px">
        <el-form-item label="公钥" prop="public_key">
          <el-input
            v-model="loginDto.public_key"
            type="textarea"
            placeholder="请输入公钥"
            rows="6"
          />
        </el-form-item>
        <el-form-item label="私钥" prop="public_key">
          <el-input
            v-model="loginDto.private_key"
            type="textarea"
            placeholder="请输入私钥"
            rows="12"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="loginVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">登 录</el-button>
        <el-button type="primary" @click="toPath"> 管理员界面</el-button>
      </span>
    </el-dialog>

    <el-dialog title="注册" :visible.sync="regVisible" width="600px">
      <el-form
        ref="registerParam"
        :model="registerParam"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerParam.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="registerParam.sex"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" value="false" />
            <el-option label="女" value="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="registerParam.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="registerParam.address" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="所在单位" prop="work_unit">
          <el-input
            v-model="registerParam.work_unit"
            placeholder="请输入所在单位"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone_number">
          <el-input
            v-model="registerParam.phone_number"
            placeholder="请输入联系电话"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_number">
          <el-input
            v-model="registerParam.id_number"
            placeholder="请输入身份证号"
          />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="registerParam.email"
            placeholder="请输入电子邮箱"
          />
        </el-form-item>
        <el-form-item label="所属电表ID">
          <el-select
            v-model="registerParam.elec_meter_id"
            placeholder="请选择电表ID"
            style="width: 100%"
          >
            <el-option
              v-for="item in elecMeterIds"
              :key="item.index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="个人说明">
          <el-input
            v-model="registerParam.user_desc"
            type="textarea"
            placeholder="请输入个人说明"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="regVisible = false">取 消</el-button>
        <el-button type="primary" @click="registered(registerParam)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="注册成功" :visible.sync="reginfoVisible" width="600px">
      <span>
        <h3>注册成功，请记录你的账户信息，文件已下载在本地！</h3>
        <div>公钥：<br />{{ registerRes.public_key }}</div>
        <div>私钥：<br />{{ registerRes.private_key }}</div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clear">知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { login, register, getElecMeterIds } from "@/api/head_index";
export default {
  props: {},
  data() {
    return {
      chgPwdVisble: false,
      loginVisible: false,
      regVisible: false,
      reginfoVisible: false,
      loginDto: {
        public_key: "",
        private_key: "",
      },
      isLogin: localStorage.getItem("Token"),
      userDate: {
        name: localStorage.getItem("Name"),
      },
      elecMeterIds: undefined,
      registerParam: {
        name: "",
        sex: undefined,
        age: "",
        address: "",
        work_unit: "",
        email: "",
        phone_number: "",
        id_number: "",
        elec_meter_id: "",
        user_desc: "",
      },
      registerRes: {
        public_key: "",
        private_key: "",
      },
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请输入性别", trigger: "change" }],
        age: [
          { message: "请输入年龄", trigger: "blur" },
          {
            pattern: /^-?\d+\.?\d*$/,
            message: "年龄必须是数字",
            trigger: "blur",
          },
        ],
        address: [{ message: "请输入地址", trigger: "blur" }],
        work_unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
        email: [{ message: "请输入电子邮箱", trigger: "blur" }],
        phone_number: [
          { message: "请输入电话", trigger: "blur" },
        ],
        id_number: [{ message: "请输入身份证号码", trigger: "blur" }],
      },
    };
  },
  // DOM 渲染完成触发
  mounted() {
    if (!this.isLogin) {
      this.getElecMeterId();
    }
  },
  methods: {
    getElecMeterId() {
      getElecMeterIds().then((res) => {
        this.elecMeterIds = res.data;
      });
    },
    clear() {
      this.registerRes = {
        public_key: "",
        private_key: "",
      };
      this.registerParam = {
        name: "",
        sex: undefined,
        age: "",
        address: "",
        work_unit: "",
        email: "",
        phone_number: "",
        id_number: "",
        elec_meter_id: "",
        user_desc: "",
      };
      this.regVisible = false;
      this.reginfoVisible = false;
    },
    handleCommand(command) {
      switch (command) {
        case "2": // 退出登录
          this.isLogin = false;
          this.getElecMeterId();
          localStorage.removeItem("Token");
          localStorage.removeItem("Name");
          this.$message.success("退出成功！");
          location.reload();
          break;
      }
    },
    onSubmit() {
      if (!this.loginDto.public_key || !this.loginDto.private_key) {
        this.$message.error("私钥或者公钥为空，请填写。");
        return;
      }
      login(this.loginDto)
        .then((res) => {
          this.$message.success("登录成功！");

          localStorage.setItem("Token", res.data.token);
          localStorage.setItem("Name", res.data.name);
          //  当前用户名更新
          this.userDate.name = res.data.name;

          this.loginDto.public_key = "";
          this.loginDto.private_key = "";

          this.loginVisible = false;
          this.isLogin = true;
          location.reload();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    registered(registerParam) {
      this.$refs.registerParam.validate((valid) => {
        if (valid) {
          register(registerParam).then((res) => {
            this.registerRes = res.data;
            this.reginfoVisible = true;
            this.sequenceDownload();
          });
        } else {
          return false;
        }
      });

      // if (
      //   this.registerParam.name === "" ||
      //   this.registerParam.sex === undefined ||
      //   this.registerParam.age === "" ||
      //   this.registerParam.address === "" ||
      //   this.registerParam.work_unit === "" ||
      //   this.registerParam.email === "" ||
      //   this.registerParam.phone_number === "" ||
      //   this.registerParam.id_number === "" ||
      //   this.registerParam.elec_meter_id === ""
      // ) {
      //   this.$message.error("数据请填写完整！");
      //   return;
      // }
      // if (
      //   !/(^[1-9]\d*$)/.test(this.registerParam.age) ||
      //   this.registerParam.age > 120
      // ) {
      //   this.$message.error("年龄格式不正确！");
      //   return;
      // }
    },
    sequenceDownload() {
      var element = document.createElement("a");
      var message = "";
      var data = this.registerRes;
      message += "公钥:" + "\n" + data.public_key + "\n";
      message += "私钥:" + "\n" + data.private_key;
      element.setAttribute(
        "href",
        "data:text/plain;charset=utf-8," + encodeURIComponent(message)
      );
      element.setAttribute("download", "注册信息");
      element.style.display = "none";
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    },
    toPath() {
      window.location.href = "http://47.104.251.136:7777/m_login";
    },
    toPath1() {
      window.location.href = "http://43.138.40.135/";
    },
    toPath2() {
      window.location.href = "http://47.104.251.136:7778/";
    },
  },
};
</script>
<style>
.flex-grow {
  flex-grow: 1;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-arrow-down {
  font-size: 12px;
}
/* 子菜单宽度 */
.el-menu--collapse .el-menu .el-submenu,
.el-menu--popup {
  min-width: 90px !important;
}
</style>
